package com.whcoding.easyexcel.converter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.whcoding.easyexcel.constant.DeptTypeEnum;

/**
 * @program: spring-boot-learning
 * @description:excel性别转换器
 * @author: whcoding
 * @create: 2022-06-28 20:30
 **/
public class DeptTypeConverter implements Converter<Integer> {
	@Override
	public Class<?> supportJavaTypeKey() {
		//对象属性类型
		return Integer.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		//CellData属性类型
		return CellDataTypeEnum.STRING;
	}

	/**
	 * 导入 将deptType 转为数字
	 *
	 * @param context
	 * @return
	 */
	@Override
	public Integer convertToJavaData(ReadConverterContext<?> context) {
		//CellData转对象属性
		String cellStr = context.getReadCellData().getStringValue();
		if (StrUtil.isEmpty(cellStr)) return null;
		if (DeptTypeEnum.ONE_LEVEL_DEPT.getName().equals(cellStr)) {
			return DeptTypeEnum.ONE_LEVEL_DEPT.getIndex();
		} else if (DeptTypeEnum.SECOND_LEVEL_DEPT.getName().equals(cellStr)) {
			return DeptTypeEnum.SECOND_LEVEL_DEPT.getIndex();
		} else if (DeptTypeEnum.THREE_LEVEL_DEPT.getName().equals(cellStr)) {
			return DeptTypeEnum.THREE_LEVEL_DEPT.getIndex();
		} else {
			return null;
		}
	}

	/**
	 * 导出时 将deptType 转为中文
	 *
	 * @param context
	 * @return
	 */
	@Override
	public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) {
		//对象属性转CellData
		Integer cellValue = context.getValue();
		if (cellValue == null) {
			return new WriteCellData<>("");
		}
		if (cellValue == 1) {
			return new WriteCellData<>(DeptTypeEnum.ONE_LEVEL_DEPT.getName());
		} else if (cellValue == 2) {
			return new WriteCellData<>(DeptTypeEnum.SECOND_LEVEL_DEPT.getName());
		} else if (cellValue == 3) {
			return new WriteCellData<>(DeptTypeEnum.THREE_LEVEL_DEPT.getName());
		} else {
			return new WriteCellData<>("");
		}
	}
}

